package com.tangguangdi.base.core.config;


import com.tangguangdi.base.common.core.AppMode;
import com.tangguangdi.base.core.controller.MatrixApiController;
import com.tangguangdi.base.core.properties.CoreProperties;
import com.tangguangdi.base.core.register.ClusterModeServer;
import com.tangguangdi.base.core.register.ModeServer;
import com.tangguangdi.base.core.register.StandaloneModeServer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * 启动类
 */
@Configuration
@PropertySource("classpath:/bootstrap.properties")
public class CoreAutoConfiguration {

    /**
     * 无参构造器
     */
    public CoreAutoConfiguration(){}

    /**
     * YML配置
     * @return 核心配置
     */
    @Bean
    @ConfigurationProperties(prefix = "max.core")
    public CoreProperties coreProperties() {
        return new CoreProperties();
    }

    /**
     * redis服务
     * @param factory redis连接对象
     * @return RedisTemplate
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }

    /**
     * 模式服务
     * @param coreProperties 核心配置
     * @return ModeServer 实例化模式
     */
    @Bean
    public ModeServer modeServer(CoreProperties coreProperties) {
        if(coreProperties.getAppMode() == AppMode.Cluster) return new ClusterModeServer(coreProperties);
        return new StandaloneModeServer(coreProperties);
    }

    /**
     * 接口服务
     * @return ApiController
     */
    @Bean
    public MatrixApiController codeController() {
        return new MatrixApiController();
    }

}
